// PPG分析页面Vue应用
const { createApp } = Vue;
const { ElMessage, ElMessageBox } = ElementPlus;

const app = createApp({
    data() {
        return {
            fileList: [],
            samplingRate: 25,
            ppgAlgorithm: 'custom',
            isAnalyzing: false,
            analysisResults: [], // 修改为analysisResults以匹配HTML模板
            errorMessage: '',
            analysisLogs: [],
            isDragOver: false,
            sidebarShow: true,
            showColumnManager: false,
            
            // PPG列分类配置
            columnCategories: {
                basic: ['filename', 'data_points', 'duration_min'],
                hr: ['peak_count', 'mean_hr_bpm', 'dominant_freq_hz', 'dominant_freq_hr_bpm', 'hr_band_power_ratio'],
                quality: ['signal_quality_score', 'snr_db'],
                hrv_time: ['mean_nn_ms', 'sdnn_ms', 'rmssd_ms', 'pnn50_percent', 'pnn20_percent', 'triangular_index'],
                hrv_freq: ['vlf_power_ms2', 'lf_power_ms2', 'hf_power_ms2', 'total_power_ms2', 'lf_nu', 'hf_nu', 'lf_hf_ratio']
            },
            
            categorySelection: {
                basic: true,
                hr: true,
                quality: true,
                hrv_time: false,
                hrv_freq: false
            },
            
            visibleColumns: {
                filename: true,
                data_points: true,
                duration_min: true,
                peak_count: true,
                mean_hr_bpm: true,
                signal_quality_score: true,
                snr_db: true,
                dominant_freq_hz: false,
                dominant_freq_hr_bpm: false,
                hr_band_power_ratio: false,
                mean_nn_ms: true,
                sdnn_ms: true,
                rmssd_ms: true,
                pnn50_percent: true,
                pnn20_percent: false,
                triangular_index: false,
                vlf_power_ms2: false,
                lf_power_ms2: true,
                hf_power_ms2: true,
                total_power_ms2: false,
                lf_nu: false,
                hf_nu: false,
                lf_hf_ratio: true
            }
        };
    },
    methods: {
        // 文件处理方法
        addFileToList(files) {
            for (let file of files) {
                if (this.fileList.some(f => f.name === file.name)) {
                    this.$message.warning(`文件 ${file.name} 已存在`);
                    continue;
                }
                
                this.fileList.push({
                    name: file.name,
                    size: file.size,
                    status: 'pending',
                    progress: 0,
                    file: file
                });
            }
        },

        handleFileChange(event) {
            const files = Array.from(event.target.files);
            this.addFileToList(files);
            event.target.value = '';
        },

        clearFiles() {
            if (this.isAnalyzing) {
                this.$message.warning('分析进行中，无法清空文件列表');
                return;
            }
            this.fileList = [];
            this.analysisResults = [];
            this.clearLogs();
        },

        removeFile(index) {
            if (this.isAnalyzing) {
                this.$message.warning('分析进行中，无法删除文件');
                return;
            }
            this.fileList.splice(index, 1);
        },

        // 简化的批量分析方法
        async startBatchAnalysis() {
            if (this.fileList.length === 0) {
                this.$message.warning('请先选择文件');
                return;
            }

            if (this.isAnalyzing) {
                this.$message.warning('分析正在进行中，请等待完成');
                return;
            }

            this.isAnalyzing = true;
            this.analysisResults = [];
            this.clearLogs();
            
            // 添加开始分析日志
            this.addLog('info', `开始分析 ${this.fileList.length} 个文件`);
            this.addLog('info', `采样率: ${this.samplingRate} Hz, 算法: ${this.ppgAlgorithm}`);

            try {
                // 准备FormData
                const formData = new FormData();
                for (let fileItem of this.fileList) {
                    formData.append('files', fileItem.file);
                    fileItem.status = 'analyzing';
                    fileItem.progress = 0;
                }
                
                // 添加分析参数
                formData.append('sampling_rate', this.samplingRate);
                formData.append('algorithm', this.ppgAlgorithm);

                this.addLog('info', '正在上传文件并开始分析...');

                // 发送分析请求
                const response = await axios.post('/api/ppg/analyze', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                    onUploadProgress: (progressEvent) => {
                        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                        this.fileList.forEach(file => {
                            if (file.status === 'analyzing') {
                                file.progress = Math.min(progress, 90); // 上传进度最多到90%
                            }
                        });
                    }
                });

                if (response.data.success) {
                    this.addLog('success', '文件上传完成，开始处理...');
                    
                    // 更新文件状态
                    this.fileList.forEach(file => {
                        file.status = 'completed';
                        file.progress = 100;
                    });

                    // 处理结果
                    if (response.data.success && response.data.results && response.data.results.length > 0) {
                        // 将结果添加到表格
                        this.analysisResults = response.data.results;
                        
                        const successCount = response.data.results.filter(r => r.processing_success).length;
                        const failCount = response.data.results.length - successCount;
                        
                        if (successCount > 0) {
                            this.addLog('success', `成功分析: ${successCount} 个文件`);
                        }
                        if (failCount > 0) {
                            this.addLog('warning', `分析失败: ${failCount} 个文件`);
                        }

                        this.$message.success(`分析完成！共处理 ${response.data.results.length} 个文件`);
                    } else {
                        this.addLog('warning', '分析完成，但没有获取到结果');
                        this.$message.warning('分析完成，但没有获取到结果');
                    }
                } else {
                    this.addLog('error', response.data.message || '分析失败');
                    this.$message.error(response.data.message || '分析失败');
                    
                    // 更新文件状态为失败
                    this.fileList.forEach(file => {
                        file.status = 'failed';
                        file.progress = 0;
                    });
                }
            } catch (error) {
                console.error('分析错误:', error);
                const errorMsg = error.response?.data?.message || error.message || '分析过程中发生错误';
                this.addLog('error', `分析失败: ${errorMsg}`);
                this.$message.error('分析失败: ' + errorMsg);
                
                // 更新文件状态为失败
                this.fileList.forEach(file => {
                    file.status = 'failed';
                    file.progress = 0;
                });
            } finally {
                this.isAnalyzing = false;
            }
        },

        // 日志管理方法
        addLog(type, message) {
            const timestamp = new Date().toLocaleTimeString();
            this.analysisLogs.push({
                type: type,
                message: message,
                timestamp: timestamp
            });
            
            // 自动滚动到底部
            this.$nextTick(() => {
                const logContainer = this.$refs.logContainer;
                if (logContainer) {
                    logContainer.scrollTop = logContainer.scrollHeight;
                }
            });
        },

        clearLogs() {
            this.analysisLogs = [];
        },

        getLogClass(type) {
            switch (type) {
                case 'error': return 'log-error';
                case 'warning': return 'log-warning';
                case 'success': return 'log-success';
                default: return 'log-info';
            }
        },

        // 文件上传相关方法
        triggerFileUpload() {
            this.$refs.fileInput.click();
        },
        
        handleFileSelect(event) {
            const files = Array.from(event.target.files || []);
            this.addFileToList(files);
            event.target.value = '';
        },
        
        handleDrop(event) {
            event.preventDefault();
            this.isDragOver = false;
            const files = Array.from(event.dataTransfer.files || []);
            this.addFileToList(files);
        },

        handleDragOver(event) {
            event.preventDefault();
            this.isDragOver = true;
        },

        handleDragLeave(event) {
            event.preventDefault();
            this.isDragOver = false;
        },

        // 文件状态和格式化方法
        getFileTypeColor(type) {
                switch(type) {
                    case 'json': return 'success';
                    case 'csv': return 'warning';
                    case 'txt': return 'info';
                    default: return 'info';
                }
        },

        formatFileSize(size) {
            if (!size) return '-';
            if (size < 1024) return size + ' B';
            if (size < 1024 * 1024) return (size/1024).toFixed(1) + ' KB';
            return (size/1024/1024).toFixed(1) + ' MB';
        },

        getStatusType(status) {
            switch (status) {
                case 'pending': return 'info';
                case 'analyzing': return 'warning';
                case 'completed': return 'success';
                case 'failed': return 'danger';
                default: return 'info';
            }
        },

        getStatusText(status) {
            switch (status) {
                case 'pending': return '待分析';
                case 'analyzing': return '分析中';
                case 'completed': return '已完成';
                case 'failed': return '失败';
                default: return '未知';
            }
        },

        // 结果导出方法
        exportResults(command) {
            if (!this.analysisResults || this.analysisResults.length === 0) {
                this.$message.warning('暂无可导出数据');
                return;
            }

            // 排除处理状态相关的字段
            const excludeColumns = ['processing_success', 'error_message', 'status', 'progress'];

            // 获取可见列，并过滤掉不需要导出的字段
            const visibleCols = Object.entries(this.visibleColumns)
                .filter(([k, v]) => v && !excludeColumns.includes(k))
                .map(([k]) => k);

            // 准备导出数据，只包含分析结果数据
            const exportData = this.analysisResults.map(result => {
                const row = {};
                visibleCols.forEach(col => {
                    // 确保只导出存在的分析数据字段
                    if (result.hasOwnProperty(col) && !excludeColumns.includes(col)) {
                        row[col] = result[col] || '';
                    }
                });
                return row;
            });

            if (command === 'csv') {
                this.exportToCSV(exportData, visibleCols);
            }
        },

        exportToCSV(data, columns) {
            // 列标题映射
            const columnLabels = {
                filename: '文件名',
                data_points: '数据点数',
                duration_min: '记录时长(分钟)',
                peak_count: '峰值数量',
                mean_hr_bpm: '平均心率(BPM)',
                signal_quality_score: '信号质量评分',
                snr_db: '信噪比(dB)',
                dominant_freq_hz: '主频率(Hz)',
                dominant_freq_hr_bpm: '主频率心率(BPM)',
                hr_band_power_ratio: '心率频段功率比(%)',
                mean_nn_ms: 'MeanNN(ms)',
                sdnn_ms: 'SDNN(ms)',
                rmssd_ms: 'RMSSD(ms)',
                pnn50_percent: 'pNN50(%)',
                pnn20_percent: 'pNN20(%)',
                triangular_index: '三角指数',
                vlf_power_ms2: 'VLF功率(ms²)',
                lf_power_ms2: 'LF功率(ms²)',
                hf_power_ms2: 'HF功率(ms²)',
                total_power_ms2: '总功率(ms²)',
                lf_nu: 'LF标准化单位',
                hf_nu: 'HF标准化单位',
                lf_hf_ratio: 'LF/HF比值'
            };

            const headers = columns.map(col => columnLabels[col] || col).join(',');
            const rows = data.map(row => 
                columns.map(col => {
                    const value = row[col];
                    if (value === undefined || value === null) return '';
                    const str = String(value);
                    if (str.includes(',') || str.includes('\n') || str.includes('"')) {
                        return '"' + str.replace(/"/g, '""') + '"';
                    }
                    return str;
                }).join(',')
            ).join('\n');

            const csv = '\uFEFF' + headers + '\n' + rows; // 添加BOM以支持中文
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `ppg_analysis_results_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            this.$message.success('CSV导出成功');
        },

        // 数据格式化方法
        formatNumber(value, decimals = 0) {
            if (value === null || value === undefined || value === '') return '-';
            const num = Number(value);
            if (isNaN(num)) return '-';
            return num.toFixed(decimals);
        },

        formatDuration(minutes) {
            if (!minutes) return '-';
            const num = Number(minutes);
            if (isNaN(num)) return '-';
            return num.toFixed(1) + ' 分钟';
        },

        formatPercentage(value) {
            if (value === null || value === undefined || value === '') return '-';
            const num = Number(value);
            if (isNaN(num)) return '-';
            return (num * 100).toFixed(1) + '%';
        },

        // 表格排序处理
        handleSortChange({ column, prop, order }) {
            // 这里可以实现排序逻辑，目前使用Element Plus的默认排序
            console.log('排序变化:', { column, prop, order });
        },

        // 状态处理方法
        getStatusType(success) {
            return success ? 'success' : 'danger';
        },

        getStatusText(success) {
            return success ? '成功' : '失败';
        },

        // 列管理方法
        toggleCategoryColumns(category) {
            const columns = this.columnCategories[category] || [];
            const checked = this.categorySelection[category];
            columns.forEach(c => { 
                this.visibleColumns[c] = checked; 
            });
        },
        
        isCategoryFullySelected(category) {
            const columns = this.columnCategories[category] || [];
            return columns.every(c => this.visibleColumns[c]);
        },
        
        isCategoryIndeterminate(category) {
            const columns = this.columnCategories[category] || [];
            const selectedCount = columns.filter(c => this.visibleColumns[c]).length;
            return selectedCount > 0 && selectedCount < columns.length;
        },

        resetColumns() {
            // 重置为默认显示状态
            this.visibleColumns = {
                filename: true,
                data_points: true,
                duration_min: true,
                peak_count: true,
                mean_hr_bpm: true,
                signal_quality_score: true,
                snr_db: true,
                dominant_freq_hz: false,
                dominant_freq_hr_bpm: false,
                hr_band_power_ratio: false,
                mean_nn_ms: true,
                sdnn_ms: true,
                rmssd_ms: true,
                pnn50_percent: true,
                pnn20_percent: false,
                triangular_index: false,
                vlf_power_ms2: false,
                lf_power_ms2: true,
                hf_power_ms2: true,
                total_power_ms2: false,
                lf_nu: false,
                hf_nu: false,
                lf_hf_ratio: true
            };
            
            // 更新分类选择状态
            this.categorySelection = {
                basic: true,
                hr: true,
                quality: true,
                hrv_time: false,
                hrv_freq: false
            };
            
            this.$message.success('已重置为默认列显示');
        },

        applyColumnSettings() {
            this.showColumnManager = false;
            this.$message.success('列显示设置已应用');
        }
    },
    
    computed: {
        sidebarCollapsed() {
            return !this.sidebarShow;
        },
        
        logPanelCollapsed() {
            return false; // 简化版本中日志面板始终展开
        }
    },

    mounted() {
        // 初始化菜单和头部
        if (typeof window.MenuConfig !== 'undefined' && typeof window.MenuConfig.initializePageMenu === 'function') {
            window.MenuConfig.initializePageMenu('ppg-analysis.html');
        }
        
        if (typeof window.CommonHeader !== 'undefined' && typeof window.CommonHeader.initHeader === 'function') {
            window.CommonHeader.initHeader('header-container', {
                title: 'S1生理数据分析工具',
                subtitle: 'PPG指标解析'
            });
        }
    }
});

// 使用Element Plus
app.use(ElementPlus);

// 挂载应用
app.mount('#app');